package com.pod5.skype.worker;

import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.io.*;
import java.nio.channels.spi.*;
import java.nio.charset.*;
import java.util.LinkedList;
import java.lang.*;


public class Client
{
    public SocketChannel client = null;
    public InetSocketAddress isa = null;
    private ModifyXMLFileWorker modifyShared;
    private String nextIP = null;
    private Boolean stop = false;
    public RecvThread rt = null;
    private String connectionIp;
    
    private LinkedList<String> masterList;
    

    public Client(String fileLocation)
    {
    	masterList = new LinkedList<String>();
    	masterList.add("128.189.244.88");
    	modifyShared = new ModifyXMLFileWorker(fileLocation);
    }
    
	public void makeConnection()
    {
			setupConnection();
			receiveMessage();
			while (!stop)
			{
				if(nextIP != null)
				{
					if(nextIP == "quit")
						stop = true;
					else
					{
						//Run script to login Skype - will be one behind the previous crawl...
//						Runtime r = Runtime.getRuntime();
//						Process autoSkype = null;
//						try {
//							autoSkype = r.exec("./scripts/auto-skype");
//						} catch (IOException e1) {
//							// TODO Auto-generated catch block
//							e1.printStackTrace();
//						}
//						try {
//							autoSkype.waitFor();
//						} catch (InterruptedException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
						LinkedList<String> insRawIP = modifyShared.modifySkypeHostCache(nextIP);
						
						//Send Result
						sendMessage(insRawIP);
						nextIP = null;
					}
				}
			}
			interruptThread();



		try
		{
			client.close();
			System.exit(0);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
    }
	
	private void setupConnection(){
		if(!masterList.isEmpty())
		{
			connectionIp = masterList.remove();
			try
			{
				client = SocketChannel.open();
				isa = new InetSocketAddress(connectionIp, 5050);
				client.connect(isa);
				client.configureBlocking(false);
			}
			catch(UnknownHostException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			
			LinkedList<String> tempList = new LinkedList<String>();
			tempList.add("Ready");
			sendMessage(tempList);
		}
		else
			stop = true;
	}
    
	public void sendMessage(LinkedList<String> inRawIP)
    {
		System.out.println("Inside SendMessage");
        ByteBuffer bytebuf = ByteBuffer.allocate(1024);
		int nBytes = 0;
		try
		{
			
			while(!inRawIP.isEmpty())
			{
				bytebuf = ByteBuffer.wrap((inRawIP.remove()+":").getBytes());
				nBytes += client.write(bytebuf);
				System.out.println("nBytes is "+nBytes);

				bytebuf.clear();
			}
			
			bytebuf = ByteBuffer.wrap("EOF".getBytes());
			nBytes += client.write(bytebuf);
			System.out.println("nBytes is "+nBytes);

			bytebuf.clear();
	    
		}
        catch(IOException e)
		{
			e.printStackTrace();
			System.out.println("Extablishing a connection with a different Host, wait 4 mins before attempting");
			try {
				Thread.sleep(1000*60*4);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		System.out.println("Wrote "+nBytes +" bytes to the server");
		
    }

    public static void main(String args[])
    {
//    	Client cl = new Client(System.getenv("HOME")+"/.Skype/shared.xml"); //For Linux
		Client cl = new Client("C:/Users/Mark/AppData/Roaming/Skype/shared.xml");
		cl.makeConnection();
    }

    public void receiveMessage()
    {
		rt = new RecvThread("Receive THread",client);
		rt.start();

    }

    public void interruptThread()
    {
		rt.val = false;
    }
    
    public class RecvThread extends Thread
    {
		public SocketChannel sc = null;
		public boolean val = true;
	
		public RecvThread(String str,SocketChannel client)
		{
			super(str);
			sc = client;
		}
	
		public void run() {

			System.out.println("Inside receivemsg");
			ByteBuffer buf = ByteBuffer.allocate(1024);
			try
			{
				while (val)
				{
					if(nextIP == null)
					{
						while ( (client.read(buf)) > 0 ){
							buf.flip();
							Charset charset = Charset.forName("us-ascii");
							CharsetDecoder decoder = charset.newDecoder();
							CharBuffer charBuffer = decoder.decode(buf);
							nextIP = charBuffer.toString();
							buf.flip();
							
						}
					}
				}
			
			}
			catch(IOException e)
			{
				e.printStackTrace();
				System.out.println("Extablishing a connection with a different Host, wait 3 mins before attempting");
				try {
					Thread.sleep(1000*60*3);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				setupConnection(); //Let this thread establish the connection, since it is checking more frequently
			}
            

		}
    }
    
}
